package com.itheima.thread.常用方法.demo5;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
    lock需要手动上解锁,解锁必须放在finally中.


* */
public class Ticket implements Runnable {
    private int ticket = 100;
    private Lock lock = new ReentrantLock();


    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if (ticket <= 0){
                    break;
                }else {
                    Thread.sleep(10);
                    ticket--;
                    System.out.println(Thread.currentThread().getName() + "正在卖票,余票还有" + ticket + " 张");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
